<template>
  <div>
    <Breadcrumb :opt-data="analyzeFuncOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="analyzeFuncData"
          :custom-empty="true"
          @pageChanged="getAnalyzeFuncData"
          @sizeChanged="getAnalyzeFuncData"
          @filterChange="getAnalyzeFuncData">
          <EmptyContent slot="empty" :opt-data="analyzeFuncOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditAnalyzeFunc ? '新增' : '编辑'}自定义函数`"
        :close-on-click-modal="false"
        :visible.sync="showAnalyzeFuncDialog"
        width="920px"
        center
        @close="analyzeFuncFormCanceled">
        <el-form
          v-loading="analyzeFuncFormLoading"
          :ref="analyzeFuncFormRef"
          :model="analyzeFuncForm"
          :rules="analyzeFuncFormRules"
          size="small"
          label-width="80px">
          <el-form-item label="方法类型" prop="type">
            <el-radio-group v-model="analyzeFuncForm.type">
              <el-radio :label="func.value" :key="idx" v-for="(func, idx) in commonConfig.analyzeFuncType">
                {{func.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="方法标题" prop="name">
            <el-input v-model="analyzeFuncForm.name" placeholder="请填写方法标题"></el-input>
          </el-form-item>
          <el-form-item label="方法详情" prop="function">
            <CodeEditor v-if="reFresh" v-model="analyzeFuncForm.function" class="mar-top"></CodeEditor>
            <!--  :value="analyzeFuncForm.function" -->
            <span v-if="/[']/.test(analyzeFuncForm.function)" class="font-color-danger" style="margin-left: 130px"> 注意：自定义函数中不可包含（'），请检查后提交！</span>
          </el-form-item>
          <!-- <el-form-item label="解析详细" prop="function">
            <el-input type="textarea" :rows="4" v-model="analyzeFuncForm.function" placeholder="请填写解析详细"></el-input>
          </el-form-item> -->
          <el-form-item label="解码示例结构" class="mar-top-20" v-if="analyzeFuncForm.type=='decode'">
            <el-input type="textarea" :rows="4" v-model="analyzeFuncForm.payloadDemo"
                      placeholder="请填写解码示例结构"></el-input>
          </el-form-item>
          <el-form-item label="备注" class="mar-top-20">
            <el-input type="textarea" v-model="analyzeFuncForm.remarks" placeholder="请填写备注"></el-input>
          </el-form-item>

          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="analyzeFuncFormCanceled">取消</el-button>
              <el-button v-if="!(/[']/.test(analyzeFuncForm.function))" size="medium" type="primary"
                         @click="analyzeFuncFormSubmitted">提交
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {msgCode} from "@/config/string";
  import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import analyzeFuncTableCfg from "@/config/table/analyzeFunc";
  import EZTable from '@/components/table/EZTable';
  import CodeEditor from '@/components/IDE/CodeEditor';

  export default {
    name: "AnalyzeFunc",
    components: {
      EZTable, CodeEditor
    },
    data() {
      return {
        commonConfig: commonConfig,
        tableLoading: true,
        tableId: tableIdConfig.analyzeFunc,
        tableHdl: null,
        analyzeFuncData: [],
        showAnalyzeFuncDialog: false,
        analyzeFuncFormLoading: false,
        analyzeFuncForm: {},
        editScriptType: 'javascript',
        analyzeFuncFormRules: {
          type: [
            {required: true, message: '请选择方法类型', trigger: ['blur', 'change']}
          ],
          name: [
            {required: true, message: '请填写方法标题', trigger: ['blur', 'change']}
          ],
          function: [
            {required: true, message: '请填写解析详细', trigger: ['blur', 'change']}
          ],
        },
        analyzeFuncFormRef: 'analyzeFuncFormRef',
        isEditAnalyzeFunc: false,
        editFunction: '',
        reFresh: true
      }
    },
    computed: {
      analyzeFuncOptData() {
        return [
          {
            type: 'btn',
            label: '新增自定义函数',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initAnalyzeFuncForm();
      this.getAnalyzeFuncData();
    },
    methods: {
      reFreshChild() {
        this.reFresh = false
        this.$nextTick(() => {
          this.reFresh = true
        })
      },
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, analyzeFuncTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const analyzeFunc = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showAnalyzeFuncDialog = true;
              this.isEditAnalyzeFunc = true;
              this.analyzeFuncForm = deepCopyWithJson(analyzeFunc);
              this.editFunction = this.analyzeFuncForm.function
              this.reFreshChild()
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteAnalyzeFunc(analyzeFunc);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initAnalyzeFuncForm() {
        this.analyzeFuncForm = {
          type: 'encode',
          name: '',
          function: '',
          remarks: '',
        }
        this.editFunction = ""
      },
      resetAnalyzeFuncForm() {
        this.initAnalyzeFuncForm();
        const analyzeFuncForm = this.$refs[this.analyzeFuncFormRef];
        analyzeFuncForm && analyzeFuncForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditAnalyzeFunc && this.resetAnalyzeFuncForm();
        this.showAnalyzeFuncDialog = true;
        this.isEditAnalyzeFunc = false;
        this.reFreshChild()
      },
      getAnalyzeFuncData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.analyzeFunc.analyzeFuncList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.analyzeFuncData = data;
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteAnalyzeFunc(analyzeFunc = {}) {
        confirmHandle({label: `确定要删除自定义函数：${analyzeFunc.name} 吗?`}).then(() => {
          API.analyzeFunc.analyzeFuncDelete({_id: analyzeFunc._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '自定义函数'});
            this.tableHdl.judgeTableMatched();
            this.getAnalyzeFuncData();
            this.resetAnalyzeFuncForm();
          });
        }).catch(() => {
        });
      },
      analyzeFuncFormCanceled() {
        this.resetAnalyzeFuncForm()
        this.showAnalyzeFuncDialog = false;
        this.$nextTick(() => {
          this.reFresh = false
        })
      },
      analyzeFuncFormSubmitted() {
        this.$refs[this.analyzeFuncFormRef].validate((valid) => {
          if (!valid) return;
          this.analyzeFuncFormLoading = true;
          if (!this.isEditAnalyzeFunc) {
            API.analyzeFunc.analyzeFuncAdd({...this.analyzeFuncForm}).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '定义函数'});
              this.showAnalyzeFuncDialog = false;
              this.analyzeFuncFormLoading = false;
              this.getAnalyzeFuncData();
              this.resetAnalyzeFuncForm();
            }).catch(err => {
              console.log('err', err)
              this.analyzeFuncFormLoading = false;
            });
          } else {
            API.analyzeFunc.analyzeFuncEdit({...this.analyzeFuncForm}).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '定义函数'});
              this.showAnalyzeFuncDialog = false;
              this.analyzeFuncFormLoading = false;
              this.getAnalyzeFuncData();
              this.resetAnalyzeFuncForm();
            }).catch(err => {
              console.log('err', err)
              this.analyzeFuncFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
